<?php
/**
 * Acces à la base de données MySql
 *
 * @copyright Copyright (c) 2013
 * @version   1.0
 * 
 * @todo commenter la classe
 **/
class DbConnection
{
	
    private $_cursor = null;
    private $_ressource = null;
    private $_errorNum = 0; 
    private $_errorMsg = '';
 
    /**
     * Shared instance
     */		
    private static $_instance;
 
    /**
    * Constructor
    * 
    * <p>Create the static instance of the singleton
	* 	and create à connection to mysqli database with AppConfig settings.
	* 	        AppConfig::getInstance().DB_HOST
	* 			AppConfig::getInstance().DB_USER 
	* 			AppConfig::getInstance().DB_PASS 
	* 			AppConfig::getInstance().DB_NAME
	* </p>
    * 
    * @name DbConnection::__construct()
    * @return void
    */    
    private function __construct () {
    	$this->_ressource = mysql_connect(AppConfig::getInstance()->DB_HOST, 
									AppConfig::getInstance()->DB_USER, 
									AppConfig::getInstance()->DB_PASS);
		mysql_select_db( AppConfig::getInstance()->DB_NAME );
 
		//set utf-8
		$this->execute("SET CHARACTER SET utf8;");
		$this->execute("SET NAMES utf8;");
    }
	
	function __destruct() {
		$this->close();
	}
	
	public function close()
	{
		if ($this->_ressource)
			mysql_close($this->_ressource);
			
		$this->_ressource = NULL;		
	}
 
    /**
    * getInstance
    * 
    * <p>Get the shared db instance</p>
    * 
    * @return database instance
    */      
    public static function getInstance () {
        if (!(self::$_instance instanceof self))
            self::$_instance = new self();
 
        return self::$_instance;
    }    
 
 
	/**
	 * Execute a query (INSERT, DELETE, UPDATE,... requests)
	 *
	 * @param sql query to execute $sql_query
	 * @param paramaters to bind $params
	 * @return mysql_query result
	 * 
	 * @todo gestion des paramètres + log de la requete et tps exec
	 */		
	public function execute ( $sql_query, $params = NULL) {
		$this->_errorNum = 0;
		$this->_errorMsg = '';
		
		$strQuery = $sql_query;
		
		if (is_array($params))
		{
			foreach ($params as $key => $value)
			{
	//			echo $key . '->' . $value;
				$strValue = $this->_transformParamValue($key, $value);
	//			echo '->' . $strValue . "</BR>";
				$strKey = '<' . $key . '/>';
				$strQuery = str_replace($strKey, $strValue, $strQuery);
			}		
		}
		
	//	echo $strQuery. "</BR>";;
		
		$this->_cursor = mysql_query( $strQuery, $this->_ressource );
		if (!$this->_cursor) {
			$this->_errorNum = mysql_errno( $this->_ressource );
			$this->_errorMsg = mysql_error( $this->_ressource ) ." SQL=".$strQuery ;
			echo $this->_errorMsg;
			return false;
		}
		return $this->_cursor;
	}
 
	public function nextRow () {
		return mysql_fetch_row($this->_cursor);
	}

	/**
	 * Get the latest id
	 *
	 * @return lastest id
	 */			
	public function getInsertId () {
		if ( $this->_ressource != null )
			return mysql_insert_id( $this->_ressource )	;
		return false;
	}
	
	/**
	 * Get the number of affected rows for le last executed query
	 *
	 * @return number of rows
	 */			
	public function getAffectedRows () {
		if ( $this->_ressource != null )
			return mysql_affected_rows( $this->_ressource )	;
		return mysql_affected_rows();
	}
	
	/**
	* 
	* 
	* @param undefined $key
	* @param undefined $value
	* 
	* @todo  A completer & a tester
	* 
*/
	private function _transformParamValue($key, $value)
	{
		
		switch ($key[0]) {
		    case 's':
				return "'" . mysql_real_escape_string($value) . "'";	
		    case 'n':
				if (is_numeric($value))
					return $value;	
				// log & excpetion
		        break;
		    case 'd':
		        // TODO
		        break;
		}
		// log & excpetion
		return '';
	}
 
} // END class